<template>
  <view>
    <view class="login">
        <uni-icons type="contact-filled" size="100" color="#AFAFAF"></uni-icons>
        <button type="primary" open-type="getUserInfo" @getuserinfo="getUserInfo" class="login-btn">一键登录</button>
      <view class="login-text">登录后尽享更多权益</view>
    </view>
    <view class="footer"></view>
  </view>
</template>

<script>
  import {mapMutations, mapState} from 'vuex'
  export default {
    name:"my-login",
    data() {
      return {
      };
    },
    computed: {
      ...mapState('user', ['redirectinfo'])
    },
    methods: {
      ...mapMutations('user', ['updateUserInfo', 'updateToken', 'updateRedirectinfo']),
      //授权后，获取用户基本信息
      getUserInfo (e) {
        // console.log(e);
        // 判断是否获取用户信息成功
        if (e.detail.errMsg === 'getUserInfo:fail auth deny') return uni.$showMsg('您取消了登录授权！')
        //调用方法，更新用户基本信息
        this.updateUserInfo(e.detail.userInfo)
        this.getToken (e.detail)
      },
      //获取code
      async getToken (info) {
        const [err, res] = await uni.login().catch(err => err)
        if(err || res.errMsg !== 'login:ok') return uni.$showMsg('登录失败1')
        //准备参数
       
        const query = {
          code: res.code,
          encryptedData: info.encryptedData,
          iv: info.iv,
          rawData: info.rawData,
          signature: info.signature
        }
        //调用接口,拿到token
       // 换取 token
           const { data: loginResult } = await uni.$http.post('/api/public/v1/users/wxlogin', query)
           if (loginResult.meta.status !== 200) {
             return uni.$showMsg('登录失败!！')
           } 
           // 2. 更新 vuex 中的 token
           this.updateToken(loginResult.message.token)
           //登陆成功后跳转到原来的页面
           this.navgateBack()
      },
      navgateBack() {
          if(this.redirectinfo && this.redirectinfo.openType === 'switchTab') {
            uni.switchTab({
              url: this.redirectinfo.from,
              complete: () => {
                this.updateRedirectinfo (null)
              }
            })
          }
      }
    },
    
  }
</script>

<style lang="scss">
  .login {
    height: 750rpx;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background-color: #f8f8f8;
    position: relative;
    overflow: hidden;
    &::after {
      content: '';
      display: block;
      width: 100%;
      height: 40px;
      background-color: white;
      border-radius: 100%;
      position: absolute; 
      bottom: 0;
      left: 0;
      transform: translateY(50%);
    }
    .login-btn {
      width: 90%;
      border-radius: 100px;
      margin: 15px 0;
      background-color: #C00000;
    }
    .login-text {
      font-size: 12px;
      color: gray;
    }
  }
  .footer {
    height: 323rpx;
    background-color: white;
  }
</style>